#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify, g
from app.models import ActivationCode, Agent
from app.models.user import User
from app.core.extensions import db
from sqlalchemy import func, desc, asc
import datetime

# 团队管理模块
team_bp = Blueprint('admin_team', __name__)


@team_bp.route('/members', methods=['GET'])
def get_team_members():
    """
    获取团队成员列表
    ---
    参数:
      - agent_id: 上级代理ID
      - page: 当前页码
      - page_size: 每页数量，默认10
      - keyword: 搜索关键词（昵称或手机号）
      - sort_field: 排序字段 (join_time, sales, name)
      - sort_order: 排序方式 (asc, desc)
    返回:
      - code: 0表示成功
      - data:
        - list: 成员列表
          - id: 成员ID
          - name: 昵称
          - avatar: 头像
          - phone: 手机号
          - join_time: 加入时间
          - level_name: 等级名称
          - level_color: 等级颜色
          - total_sales: 总销量
          - commission_rate: 分佣比例（百分比）
        - total: 总人数
    """
    agent_id = request.args.get('agent_id')
    page = int(request.args.get('page', 1))
    page_size = int(request.args.get('page_size', 10))
    keyword = request.args.get('keyword', '')
    sort_field = request.args.get('sort_field', 'join_time')
    sort_order = request.args.get('sort_order', 'desc')

    if not agent_id:
        return jsonify({"code": 1, "message": "缺失ID"})

    try:
        offset = (page - 1) * page_size

        query = Agent.query.with_entities(
            Agent.id,
            User.nick_name.label('name'),
            User.avatar_url.label('avatar'),
            User.mobile.label('phone'),
            Agent.create_time.label('join_time'),
            Agent.level,
            Agent.commission_rate,
            func.count(ActivationCode.id).label('total_sales')
        ).join(
            User, Agent.user_id == User.user_id, isouter=True
        ).outerjoin(
            ActivationCode,
            (ActivationCode.created_by == Agent.id) & (ActivationCode.used_by.isnot(None))
        ).filter(
            Agent.parent_id == agent_id
        ).group_by(
            Agent.id,
            User.nick_name,
            User.avatar_url,
            User.mobile,
            Agent.create_time,
            Agent.level,
            Agent.commission_rate
        )

        # 关键词搜索
        if keyword:
            query = query.filter(
                db.or_(
                    User.nick_name.like(f'%{keyword}%'),
                    User.mobile.like(f'%{keyword}%')
                )
            )

        # 排序处理
        if sort_field == 'join_time':
            query = query.order_by(desc(Agent.create_time) if sort_order == 'desc' else asc(Agent.create_time))
        elif sort_field == 'sales':
            query = query.order_by(desc('total_sales') if sort_order == 'desc' else asc('total_sales'))
        elif sort_field == 'name':
            query = query.order_by(desc(User.nick_name) if sort_order == 'desc' else asc(User.nick_name))

        # 总人数查询
        total_query = db.session.query(func.count(Agent.id)).filter(Agent.parent_id == agent_id)
        if keyword:
            total_query = total_query.join(
                User, Agent.user_id == User.user_id
            ).filter(
                db.or_(
                    User.nick_name.like(f'%{keyword}%'),
                    User.mobile.like(f'%{keyword}%')
                )
            )
        total = total_query.scalar() or 0

        # 获取分页数据
        members = query.offset(offset).limit(page_size).all()

        # 格式化返回数据
        member_list = []
        for member in members:
            # 获取代理等级信息
            agent = Agent.query.get(member.id)
            level_name = agent.get_level_name() if hasattr(agent, 'get_level_name') else f"等级{member.level}"
            level_color = getattr(agent, 'level_color', '') or ""

            # 格式化加入时间
            join_time_str = member.join_time.strftime('%Y-%m-%d %H:%M') if member.join_time else ''

            member_dict = {
                'id': member.id,
                'name': member.name or f"代理ID-{member.id}",  # 默认名称处理
                'avatar': member.avatar or "",  # 默认头像处理
                'phone': member.phone or "",  # 默认手机号处理
                'join_time': join_time_str,
                'level_name': level_name,
                'level_color': level_color,
                'total_sales': member.total_sales,
                'commission_rate': member.commission_rate * 100 if member.commission_rate else 0
            }
            member_list.append(member_dict)

        # 返回结果
        result = {
            "code": 0,
            "data": {
                "list": member_list,
                "total": total
            }
        }

        return jsonify(result)

    except Exception as e:
        # 错误处理
        print(f"获取团队成员列表错误: {str(e)}")
        return jsonify({"code": 500, "message": "获取团队成员列表错误"}), 500


@team_bp.route('/hierarchy', methods=['GET'])
def get_team_hierarchy():
    """
    获取团队层级结构
    ---
    参数:
      - agent_id: 代理ID
    返回:
      - code: 0表示成功
      - data:
        - hierarchy: 层级结构
          - id: 代理ID
          - name: 代理名
          - level: 代理等级
          - level_name: 等级名
          - avatar: 头像
          - phone: 电话
          - sales: 销量
          - commission_rate: 佣金率
          - children: 下级代理列表
        - stats:
          - total_members: 团队成员数
          - total_sales: 团队总销量
          - level_distribution: 等级分布
    """
    # 获取参数
    agent_id = request.args.get('agent_id')

    # 参数校验
    if not agent_id:
        return jsonify({"code": 1, "message": "缺少代理ID"})

    try:
        # 获取代理信息
        agent = Agent.query.get(agent_id)
        if not agent:
            return jsonify({"code": 1, "message": "代理不存在"}), 404

        # 构建团队层级结构
        hierarchy = build_team_hierarchy(agent)

        # 获取团队统计数据
        stats = get_team_stats(agent)

        # 返回结果
        result = {
            "code": 0,
            "data": {
                "hierarchy": hierarchy,
                "stats": stats
            }
        }

        return jsonify(result)

    except Exception as e:
        # 错误处理
        print(f"获取团队层级结构发生错误: {str(e)}")
        return jsonify({"code": 500, "message": "获取团队层级结构发生错误"}), 500


def build_team_hierarchy(agent):
    """构建代理团队层级结构"""
    # 获取代理关联的用户信息
    user = None

    # 1. 首先通过user_id查找
    if agent.user_id:
        user = User.query.filter_by(user_id=agent.user_id).first()

    # 2. 如果没有找到，尝试通过手机号查找用户
    if not user and agent.mobile:
        user = User.query.filter_by(mobile=agent.mobile).first()

    # 3. 如果还是没找到，创建一个简单对象来存储代理的name和mobile
    if not user and agent.name:
        from types import SimpleNamespace
        user = SimpleNamespace()
        user.nick_name = agent.name
        user.avatar_url = ""
        user.mobile = agent.mobile

    # 获取代理销量
    sales_count = db.session.query(func.count(ActivationCode.id)).filter(
        ActivationCode.created_by == agent.id,
        ActivationCode.status == 1  # 已激活的卡
    ).scalar() or 0

    # 构建节点
    node = {
        'id': agent.id,
        'name': agent.name or (getattr(user, 'nick_name', '') or f"代理ID-{agent.id}"),
        'level': agent.level,
        'level_name': agent.get_level_name(),
        'avatar': getattr(user, 'avatar_url', '') or "",
        'phone': getattr(user, 'mobile', '') or agent.mobile or "",
        'sales': sales_count,
        'commission_rate': agent.commission_rate * 100 if agent.commission_rate else 0,
        'children': []
    }

    # 递归处理下级代理
    for child in agent.children:
        child_node = build_team_hierarchy(child)
        node['children'].append(child_node)

    return node


def get_team_stats(agent):
    """获取团队统计数据"""
    # 获取所有团队成员
    team_members = agent.get_all_children()

    # 获取团队所有成员ID列表
    team_ids = [agent.id] + [member.id for member in team_members]

    # 计算团队总销量
    total_sales = db.session.query(func.count(ActivationCode.id)).filter(
        ActivationCode.created_by.in_(team_ids),
        ActivationCode.status == 1  # 已激活的卡
    ).scalar() or 0

    # 统计等级分布
    level_distribution = {}
    for member in team_members + [agent]:
        level_name = member.get_level_name()
        if level_name in level_distribution:
            level_distribution[level_name] += 1
        else:
            level_distribution[level_name] = 1

    return {
        'total_members': len(team_members),
        'total_sales': total_sales,
        'level_distribution': level_distribution
    }


@team_bp.route('/agent_detail', methods=['GET'])
def get_agent_detail():
    """
    获取代理详情
    ---
    参数:
      - agent_id: 代理ID
    返回:
      - code: 0表示成功
      - data:
        - id: 代理ID
        - name: 代理名
        - level: 代理等级
        - level_name: 等级名
        - avatar: 头像
        - phone: 电话
        - created_at: 创建时间
        - commission_rate: 佣金率
        - parent_id: 上级代理ID
        - parent_name: 上级代理名
        - total_sales: 总销量
        - monthly_sales: 月销量
        - team_size: 团队人数
    """
    # 获取参数
    agent_id = request.args.get('agent_id')

    # 参数校验
    if not agent_id:
        return jsonify({"code": 1, "message": "缺少代理ID"})

    try:
        # 获取代理信息
        agent = Agent.query.get(agent_id)
        if not agent:
            return jsonify({"code": 1, "message": "代理不存在"}), 404

        # 获取代理关联的用户信息
        # 调试打印
        print(f"代理关联信息agent_id={agent_id}, user_id={agent.user_id}")
        user = None

        # 1. 首先通过user_id查找
        if agent.user_id:
            user = User.query.filter_by(user_id=agent.user_id).first()

        # 2. 如果没有找到，尝试通过手机号查找用户
        if not user and agent.mobile:
            user = User.query.filter_by(mobile=agent.mobile).first()

        # 3. 如果还是没找到，创建一个简单对象来存储代理的name和mobile
        if not user and agent.name:
            from types import SimpleNamespace
            user = SimpleNamespace()
            user.nick_name = agent.name
            user.avatar_url = ""
            user.mobile = agent.mobile

        print(f"找到用户: {user}")
        if user:
            try:
                print(
                    f"用户 - 昵称:{getattr(user, 'nick_name', '无')}, 电话:{getattr(user, 'mobile', '无')}, 头像:{getattr(user, 'avatar_url', '无')}")
            except Exception as e:
                print(f"打印错误: {str(e)}")
        else:
            print("用户不存在")

        # 获取上级代理信息
        parent = Agent.query.get(agent.parent_id) if agent.parent_id else None
        parent_name = parent.name if parent else None

        # 获取团队人数
        team_size = len(agent.get_all_children())

        # 获取代理总销量
        total_sales = ActivationCode.query.with_entities(func.count(ActivationCode.id)).filter(
            ActivationCode.created_by == agent.id,
            ActivationCode.status == 1  # 已激活的卡
        ).scalar() or 0

        # 获取代理月销量
        current_month = datetime.datetime.now().strftime('%Y-%m-01 00:00:00')
        monthly_sales = db.session.query(func.count(ActivationCode.id)).filter(
            ActivationCode.created_by == agent.id,
            ActivationCode.status == 1,  # 已激活的卡
            ActivationCode.used_time >= current_month
        ).scalar() or 0

        # 构建代理详情
        agent_detail = {
            'id': agent.id,
            'name': agent.name or (getattr(user, 'nick_name', '') or f"代理ID-{agent.id}"),
            'level': agent.level,
            'level_name': agent.get_level_name(),
            'avatar': getattr(user, 'avatar_url', '') or "",
            'phone': getattr(user, 'mobile', '') or agent.mobile or "",
            'created_at': agent.create_time.strftime('%Y-%m-%d %H:%M:%S') if agent.create_time else None,
            'commission_rate': agent.commission_rate * 100 if agent.commission_rate else 0,
            'parent_id': agent.parent_id,
            'parent_name': parent_name,
            'total_sales': total_sales,
            'monthly_sales': monthly_sales,
            'team_size': team_size
        }

        # 调试打印
        print(f"代理详情: {agent_detail}")

        # 返回结果
        result = {
            "code": 0,
            "data": agent_detail
        }

        return jsonify(result)

    except Exception as e:
        # 错误处理
        import traceback
        print(f"获取代理详情发生错误: {str(e)}")
        print(traceback.format_exc())
        return jsonify({"code": 500, "message": "获取代理详情发生错误"}), 500


@team_bp.route('/agent_sales_records', methods=['GET'])
def get_agent_sales_records():
    """
    获取代理销售记录
    ---
    参数:
      - agent_id: 代理ID
      - limit: 返回记录数量
    返回:
      - code: 0表示成功
      - data:
        - records: 销售记录列表
          - id: 记录ID
          - product_name: 产品名
          - price: 价格
          - commission: 佣金
          - created_at: 创建时间
    """
    # 获取参数
    agent_id = request.args.get('agent_id')
    limit = request.args.get('limit', 10, type=int)

    # 参数校验
    if not agent_id:
        return jsonify({"code": 1, "message": "缺少代理ID"})

    try:
        # 获取代理信息
        agent = Agent.query.get(agent_id)
        if not agent:
            return jsonify({"code": 1, "message": "代理不存在"}), 404

        # 获取代理销售记录
        records_query = ActivationCode.query.with_entities(
            ActivationCode.id,
            Product.name.label('product_name'),
            Product.price,
            (Product.price * agent.commission_rate).label('commission'),
            ActivationCode.used_time.label('created_at')
        ).join(
            Product, ActivationCode.product_id == Product.id
        ).filter(
            ActivationCode.created_by == agent.id,
            ActivationCode.status == 1  # 已激活的卡
        ).order_by(
            ActivationCode.used_time.desc()
        ).limit(limit)

        records = []
        for record in records_query:
            records.append({
                'id': record.id,
                'product_name': record.product_name,
                'price': float(record.price) if record.price else 0,
                'commission': float(record.commission) if record.commission else 0,
                'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S') if record.created_at else None
            })

        # 返回结果
        result = {
            "code": 0,
            "data": {
                "records": records
            }
        }

        return jsonify(result)

    except Exception as e:
        # 错误处理
        print(f"获取代理销售记录错误: {str(e)}")
        return jsonify({"code": 500, "message": "获取代理销售记录错误"}), 500


@team_bp.route('/update_commission', methods=['POST'])
def update_agent_commission():
    """
    修改代理佣金率
    ---
    参数:
      - agent_id: 代理ID
      - commission_rate: 佣金率(0-100)
    返回:
      - code: 0表示成功
    """
    # 获取请求参数
    data = request.json
    agent_id = data.get('agent_id')
    commission_rate = data.get('commission_rate')

    # 参数校验
    if not agent_id:
        return jsonify({"code": 1, "message": "缺少代理ID"})

    if commission_rate is None:
        return jsonify({"code": 1, "message": "缺少佣金率"})

    try:
        commission_rate = float(commission_rate)
        if commission_rate < 0 or commission_rate > 100:
            return jsonify({"code": 1, "message": "佣金率必须在0-100范围内"})
    except:
        return jsonify({"code": 1, "message": "佣金率格式错误"})

    try:
        # 获取代理信息
        agent = Agent.query.get(agent_id)
        if not agent:
            return jsonify({"code": 1, "message": "代理不存在"}), 404

        # 修改佣金率
        agent.commission_rate = commission_rate / 100
        db.session.commit()

        # 返回结果
        result = {
            "code": 0,
            "message": "佣金率修改成功"
        }

        return jsonify(result)

    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        # 错误处理
        print(f"修改代理佣金率发生错误: {str(e)}")
        return jsonify({"code": 500, "message": "修改代理佣金率发生错误"}), 500


@team_bp.route('/send_message', methods=['POST'])
def send_agent_message():
    """
    发送消息给代理
    ---
    参数:
      - agent_id: 代理ID
      - message: 消息内容
    返回:
      - code: 0表示成功
    """
    # 获取请求参数
    data = request.json
    agent_id = data.get('agent_id')
    message = data.get('message')

    # 参数校验
    if not agent_id:
        return jsonify({"code": 1, "message": "缺少代理ID"})

    if not message or not message.strip():
        return jsonify({"code": 1, "message": "消息内容不能为空"})

    try:
        # 获取代理信息
        agent = Agent.query.get(agent_id)
        if not agent:
            return jsonify({"code": 1, "message": "代理不存在"}), 404

        # 检查Agent是否有关联的用户ID可以接收消息
        if agent.user_id:
            # 创建消息记录
            from app.models.system import Message
            new_message = Message(
                user_id=agent.user_id,
                title="系统消息",
                content=message.strip(),
                type="system",
                created_at=datetime.datetime.now()
            )
            db.session.add(new_message)
            db.session.commit()

            # 返回结果
            result = {
                "code": 0,
                "message": "消息发送成功"
            }
        else:
            result = {
                "code": 1,
                "message": "代理未关联用户无法发送消息"
            }

        return jsonify(result)

    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        # 错误处理
        print(f"发送消息给代理发生错误: {str(e)}")
        return jsonify({"code": 500, "message": "发送消息失败"}), 500


def init_app(app):
    app.register_blueprint(team_bp, url_prefix='/api/admin/mp/team')